import type { CommandModule, Argv } from "yargs";
import { failHandler, getPkgInfo } from "@/common";
import type { ChildCmd, Options } from "./handler";
import { handler } from "./handler";
import _curry from "lodash.curry";

const { version } = getPkgInfo();

const getCli = (cli: Argv<Options>, usage: string) => {
  return cli
    .strict()
    .usage(usage)
    .help("help")
    .version(version)
    .alias("v", "version")
    .alias("h", "help")
    .options({
      type: {
        type: "string",
        choices: [
          "major",
          "minor",
          "patch",
          "premajor",
          "preminor",
          "prepatch",
          "prerelease",
        ],
        default: "patch",
        description: "发布类型",
        alias: "t",
        demandOption: true,
      },
    })
    .options({
      push: {
        type: "boolean",
        default: true,
        description: "是否推送至远程仓库",
        alias: "p",
        demandOption: false,
      },
    })
    .fail(failHandler);
};

const builder = (cli: Argv<Options>, subCmd: ChildCmd) => {
  return getCli(
    cli,
    `Usage: $0 ${subCmd} [options]`,
  ) as unknown as Argv<Options>;
};

export const getCommand = ({
  command,
  describe,
}: {
  command: ChildCmd;
  describe: string;
}): CommandModule<any, Options> => {
  return {
    command,
    describe,
    builder: (cli) => builder(cli, command),
    handler: _curry(handler)(command),
  };
};

/*
export const createCli = async () => {
  const cli = yargs(hideBin(process.argv)) as Argv<Options>;
  const args = (await getCli(
    cli,
    l3CmdUsage,
  )) as unknown as ArgumentsCamelCase<Options>;

  return handler(args);
};
*/
